package com.test.ml.yqs.web;

import com.alibaba.fastjson.JSONObject;
import com.test.ml.yqs.entity.User;
import com.test.ml.yqs.service.SysLoginService;
import com.test.ml.yqs.service.UserService;
import com.test.ml.yqs.utills.ResultJson;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 马亮
 * @version V1.0
 * @Description: TODO
 */
@RestController
@RequestMapping("/")
public class LoginController {

    @Autowired
    private SysLoginService loginService;
    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param req
     * @param resp
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @RequestMapping(value="login",method = RequestMethod.POST)
    public ResultJson login(HttpServletRequest req, HttpServletResponse resp,@RequestParam(required = false) String username,
                            @RequestParam(required = false) String password  ) {

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            // 登录，即身份验证
            subject.login(token);
            User user = userService.findByAcount(token.getUsername());
            // 在session中存放用户信息
            subject.getSession().setAttribute("userLogin", user);
            Cookie cookie=new Cookie("JSESSIONID",subject.getSession().getId().toString());
            resp.addCookie(cookie);
            return ResultJson.buildSuccess("登录成功",user);
        } catch (IncorrectCredentialsException e) {
            return ResultJson.buildError("用户名或密码错误");
        } catch (LockedAccountException e) {
            return ResultJson.buildError("登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            return ResultJson.buildError("用户名或密码错误");
        }
    }

}